package cc.sunni.api.interceptors;

import cc.sunni.common.exception.RRException;
import cc.sunni.common.utils.RedisOperator;
import cc.sunni.common.utils.ResultEnum;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class BaseInterceptor {
    @Autowired
    public RedisOperator redis;

    public boolean verifyUserIdToken(String id, String token, String redisKeyPrefix) {

        if (StrUtil.isNotBlank(id) && StrUtil.isNotBlank(token)) {
            String redisToken = redis.get(redisKeyPrefix + ":" + id);
            if (StrUtil.isBlank(id)) {
                throw new RRException(ResultEnum.UN_LOGIN);
            } else {
                if (!redisToken.equalsIgnoreCase(token)) {
                    throw new RRException(ResultEnum.TICKET_INVALID);
                }
            }
        } else {
            throw new RRException(ResultEnum.UN_LOGIN);
        }
        return true;
    }

    // 从cookie中取值
    public String getCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return null;
        }
        for(Cookie cookie : cookies){
            if(cookie.getName().equals(key)){
                return cookie.getValue();
            }
        }
        return null;
    }

}
